<template>
    <el-main class="image-main" v-loading="loading">
        <div class="top p-3">
            <el-row :gutter="10">
                <template v-for="(item, index) in videos" :key="index">
                <el-col :span="6" :offset="0" >
                    <el-card shadow="hover" class="relative mb-3" :body-style="{ padding: 0 }"
                             :class="{ 'border-blue-500': item.checked }" >

                        <video :src="item.image" controls  class="h-[150px]" style="width: 100%"></video>

                        <div class="image-title">{{ item.title }}</div>
                        <div class="btn-alignment">
                            <el-checkbox v-if="openChoose" v-model="item.checked" @change="handleChooseChange(item)" />
                            <el-button type="primary" text @click="handleEdit(item)" v-permission="['Image,update']">
                                <el-icon class="el-icon--left" :size="14">
                                    <Edit />
                                </el-icon>
                                编辑
                            </el-button>

                            <el-popconfirm title="是否删除该图片？" confirmButtonText="确认" cancelButtonText="取消"
                                           @confirm="handleDelete(item.id)">
                                <template #reference>
                                    <el-button type="danger" class="!m-0" text v-permission="['Image,bulk_deletes']">
                                        <el-icon class="el-icon--left" :size="14">
                                            <Delete />
                                        </el-icon>删除
                                    </el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                    </el-card>
                </el-col>
                </template>
            </el-row>
        </div>

        <div class="bottom">
            <el-pagination background layout="prev,pager, next" :total="total" :current-page="currentPage" :page-size="pageSize"
                           @current-change="getData" />
        </div>
    </el-main>
    <el-dialog v-model="dialogFormVisible" title="编辑">
        <el-form :model="formEdit" :rules="rulesEdit" ref="formEditRef">
            <el-form-item label="图片标签" prop="image_label" label-width="140px">
                <el-col :span="24">
                    <el-select v-model="formEdit.image_label" placeholder="图片标签" filterable>
                        <el-option v-for="(item, index) in labelList" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                </el-col>
            </el-form-item>
            <el-form-item label="图片标题" placeholder="图片标题" prop="title" label-width="140px">
                <el-col :span="16">
                    <el-input v-model="formEdit.title" autocomplete="off" />
                </el-col>
            </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="loadingEdit" @click="handleSubmit">
          提交
        </el-button>
      </span>
        </template>
    </el-dialog>

    <!-- 图片上传组件 -->
    <el-drawer v-model="drawer" title="上传视频">
        <UploadFile :data="{ image_label: image_class_id }" @success="handleUploadSuccess" />
    </el-drawer>
</template>
<script setup>
import { ref, reactive, computed } from "vue";
import {
    getVideoList,
    patchImageTitleOtLabel,
    deleteImage,
    getImageLabelList, getVideo, getVideoLabelList, patchVideoTitleOtLabel,
} from "~/api/medias/image.js";
import { showPrompt, toast } from "~/composables/util.js";
import UploadFile from "./videoUploadFile.vue";
import { useStore } from "vuex";
import { number } from "echarts";
const store = useStore();
// 编辑 弹窗
const dialogFormVisible = ref(false);
const labelList = ref([]);
const loadingEdit = ref(false);
const formEdit = reactive({
    title: "",
    image_label: "",
    id: "",
});
// 编辑表单内容
const formEditRef = ref(null);
// 编辑验证
const rulesEdit = {
    title: [
        {
            required: true,
            message: "视频名称不能为空",
            trigger: "blur",
        },
    ],
    image_label: [
        {
            required: true,
            message: "视频名称不能为空",
            trigger: "blur",
        },
    ],
};
// 分页
const currentPage = ref(1);
const total = ref(0);
// const pageSize = ref(store.state.pageSize.ImageMain);
const pageSize = ref(10);
const list = ref([]);

// 视频/图片类
const videos = ref([])
// const images = ref([])

const loading = ref(false);
const image_class_id = ref(0);
// 上传图片
const drawer = ref(false);
const openUploadFile = () => (drawer.value = true);
// 获取数据
function getData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p;
    }

    loading.value = true;
    getVideoList(image_class_id.value,currentPage.value,pageSize.value)
        .then((res) => {
            total.value = res.data.count;
            list.value = res.data.results.map((o) => {
                o.checked = false;
                return o;
            });
            // // 切取视频类文件
            // const videoFiles = res.results.filter(item => {
            //     const cutDate = item.image.toLowerCase();
            //     return cutDate.endsWith('.mp4')
            // })
            videos.value = res.data.results
        })
        .finally(() => {
            loading.value = false;
        });
}

// 根据分类ID重新加载图片列表
const loadData = (id) => {
    currentPage.value = 1;
    image_class_id.value = id;
    getData();
};

// 编辑
const handleEdit = (item) => {
    dialogFormVisible.value = true;
    formEdit.title = item.title;
    formEdit.image_label = item.image_label;
    formEdit.id = item.id;
    getVideoLabelList(1, 100).then((res) => (labelList.value = res.results));
};
const handleSubmit = () => {
    formEditRef.value.validate((valid) => {
        if (!valid) return;
        loadingEdit.value = true;
        patchVideoTitleOtLabel(formEdit)
            .then((res) => {
                toast("修改成功");
                getData();
            })
            .finally(() => {
                loadingEdit.value = false;
                dialogFormVisible.value = false;
            });
    });
};

// 删除图片
const handleDelete = (id) => {
    loading.value = true;
    deleteImage([id])
        .then((res) => {
            toast("删除成功");
            getData();
        })
        .finally(() => {
            loading.value = false;
        });
};
const props = defineProps({
    openChoose: {
        type: Boolean,
        default: false,
    },
    limit: {
        type: Number,
        default: 1,
    },

});

// 图片类文件
const isImage = (image) => {
    return image.toLowerCase().endsWith('.jpg') || image.toLowerCase().endsWith('.jpeg') || image.toLowerCase().endsWith('.png') || image.toLowerCase().endsWith('.gif');
}

// 上传成功
const handleUploadSuccess = () => getData(1);
// 选中
const emit = defineEmits(["choose"]);
const checkedImage = computed(() => list.value.filter((o) => o.checked));
const handleChooseChange = (item) => {
    if (item.checked && checkedImage.value.length > props.limit) {
        item.checked = false;
        return toast("最多只能选中" + props.limit + "张", "error");
    }
    emit("choose", checkedImage.value);
};

defineExpose({
    loadData,
    openUploadFile,
});
</script>
<style>
.image-main {
    position: relative;
}

.image-main .top {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 50px;
    overflow-y: auto;
}

.image-main .bottom {
    position: absolute;
    bottom: 0;
    height: 50px;
    left: 0;
    right: 0;
    @apply flex items-center justify-center;
}

.image-title {
    position: absolute;
    top: 122px;
    left: -1px;
    right: -1px;
    @apply text-sm truncate text-gray-100 bg-opacity-50 bg-gray-800 px-2 py-1;
}

.btn-alignment {
    @apply flex items-center justify-center p-2;
}
</style>